<template>
  <base-modal
    class="remark-form-design"
    width="100%"
    :show="true"
    :closeable="false"
  >
    <template slot="title">
      <div class="form-builder-title">{{$t('event.setting.serviceRemark.headTitle')}}</div>
      <el-button
        class="form-builder-save-btn"
        plain
        @click="submit"
        :disabled="pending"
      >{{$t('common.base.save')}}</el-button
      >
      <button
        type="button"
        class="base-modal-header-close"
        @click="handleCancel"
      >
        <i class="iconfont icon-fe-close"></i>
      </button>
    </template>

    <!-- start 表单设计器 -->
    <div class="task-form-design" v-loading.lock="pending">
      <form-design
        ref="formDesign"
        v-model="fields"
        mode="remark"
        :common-fields="commonFields"
      ></form-design>
    </div>
  </base-modal>
</template>

<script>
import { toFormField, toField } from '@src/component/form/util';
import { getRemarkTemplate, saveRemarkTemplate } from '@src/api/ImApi';

export default {
  props: {
    visible: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      pending: false,
      fields: [], // 表单字段
      commonFields: [], // 公共字段
      mode: '',
    };
  },
  beforeMount() {
    this.getTemplate();
  },
  methods: {
    async getTemplate() {
      try {
        const { success, message, data } = await getRemarkTemplate();
        if (!success) {
          this.$message.error(message);
          return;
        }
        this.fields = this.toFormField(data);
        this.fields.forEach(item => item.isAppShow = 0);
      } catch (error) {
        console.error('get remark template error:', error);
      }
    },
    // 将后端字段转换成设计器可接受的字段
    toFormField(fields = []) {
      let sortedFields = fields.sort((a, b) => a.orderId - b.orderId);
      return toFormField(sortedFields);
    },
    handleCancel() {
      this.fields = [];
      this.$emit('update:visible', false);
    },
    packToField(origin = []) {
      let fields = toField(origin);
      fields.forEach((field, index) => {
        field.orderId = index;
      });
      return fields;
    },
    async submit() {
      try {
        const params = this.packToField(this.fields);
        const res = await saveRemarkTemplate(params);
        this.handleCancel();
        this.$message.success(this.$t('common.base.saveSuccess'));
      } catch (error) {
        this.$alert(error.message, this.$t('event.setting.serviceRemark.saveForm'));
      }
    },
  },
};
</script>

<style lang="scss" src="./RemarkFormDesign.scss"></style>
